package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Permission;
import cn.wolfcode.rbac.mapper.PermissionMapper;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IPermissionService;
import cn.wolfcode.rbac.util.PageResult;
import cn.wolfcode.rbac.util.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2020/6/10 0010.
 */

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public void delete(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Permission get(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Permission> listAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public void saveOrUpdate(Permission permission) {
        if(permission.getId() == null){
            permissionMapper.insert(permission);
        }else{
            permissionMapper.updateByPrimaryKey(permission);
        }
    }

    @Override
    public PageResult query(QueryObject queryObject) {
        //1 如果数据库中没有数据 需要分页吗? 肯定是不需要
        // selectForCount 方法返回值, 表中的数据条数
        int count = permissionMapper.selectForCount(queryObject);
        if(count == 0){
            return PageResult.DEFAULT_PAGE;
        }
        // 那么思考 如何查看数据库表是否有数据存在
        // 2 分页操作
        List<Permission> list = permissionMapper.selectForList(queryObject);
        return new PageResult(queryObject.getCurrentPage(),queryObject.getPageSize(),list,count);
    }

    @Autowired
    private ApplicationContext ctx; //Spring 容器对象
    @Override
    public void reload() {

        List<String> expressions = permissionMapper.selectExpression();
        Map<String, Object> beansWithAnnotation = ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> controllers = beansWithAnnotation.values();
        for (Object controller : controllers) {
            Method[] methods = controller.getClass().getMethods();
            for (Method method : methods) {
                RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
                if(annotation != null && !expressions.contains(annotation.values()[1])){
                    Permission p = new Permission();
                    p.setName(annotation.values()[0]);
                    p.setExpression(annotation.values()[1]);
                    permissionMapper.insert(p);
                }
            }
        }
    }

}
